import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Layout, Card, Tabs, message, Button, Input, Space } from 'antd';
import { Panel, PanelGroup, PanelResizeHandle } from 'react-resizable-panels';
import { useParams } from 'react-router-dom';
import CodeEditor from '../../components/problemDetail/CodeEditor';
import ProblemDescription from '../../components/problemDetail/ProblemDescription';
import RunResult from '../../components/problemDetail/RunResult';
import AiChat from '../../components/problemDetail/AiChat';
import ProblemDetailHeader from '../../components/problemDetail/ProblemDetailHeader';
import { SubmissionList, SubmissionDetail } from '../../components/judge';
import type { Problem } from '../../api/vo/problemDetail';
import { problemDetailApi } from '../../api/services/Problem/problemDetail';
import type { ProblemInfoVO } from '../../api/vo/problemDetail';
import type {  JudgeInfo } from '../../api/vo/problemDetail';
import type { TestCase } from '../../api/dto/problemDetail';


import './ProblemDetailPage.less';
import judgeApi from '../../api/services/Judge/judgeApi';
import type { LanguageType } from '../../api/dto/judge';

const { Content } = Layout;

// 自定义防抖函数
const debounce = <T extends (...args: any[]) => any>(
  func: T,
  wait: number
): ((...args: Parameters<T>) => void) => {
  let timeout: ReturnType<typeof setTimeout> | null = null;
  return (...args: Parameters<T>) => {
    if (timeout) clearTimeout(timeout);
    timeout = setTimeout(() => func(...args), wait);
  };
};

const ProblemDetailPage: React.FC = () => {
  const { id } = useParams<{ id: string }>();


  const [problemData, setProblemData] = useState<ProblemInfoVO | undefined>(undefined);
  const [loading, setLoading] = useState(false);
  const [studentCode, setStudentCode] = useState('');
  const [programmingLanguage, setProgrammingLanguage] = useState('cpp');
  const [errorMessage, setErrorMessage] = useState('');
  const [output, setOutput] = useState('');
  const [runResultLoading, setRunResultLoading] = useState(false);
  const [runResultActiveTab, setRunResultActiveTab] = useState('result');
  const [testCaseInput, setTestCaseInput] = useState('');
  const codeEditorRef = useRef(null);
  
  // 在线自测相关状态
  const [isOnlineTest, setIsOnlineTest] = useState(false);
  const [testCases, setTestCases] = useState<TestCase[]>([]);
  const [judgeInfo, setJudgeInfo] = useState<JudgeInfo[]>([]);
  const [memory, setMemory] = useState(0);
  const [time, setTime] = useState(0);
  const [isAccepted, setIsAccepted] = useState(false);
  const [outputList, setOutputList] = useState<string[]>([]);

  // 提交记录相关状态
  const [selectedSubmitId, setSelectedSubmitId] = useState<number | null>(null);
  const [detailModalVisible, setDetailModalVisible] = useState(false);

  // 控制面板显示状态
  const [showProblemPanel, setShowProblemPanel] = useState(true);
  const [showResultPanel, setShowResultPanel] = useState(true);
  const [showAiPanel, setShowAiPanel] = useState(false);
  const [editorPaelSize, setEditorPanelSize] = useState(50);
  const [resultPanelSize, setResultPanelSize] = useState(30);



  // 根据URL中的题目ID获取题目数据
  useEffect(() => {
    const fetchProblemData = async () => {
      if (!id) return;
      
      setLoading(true);
      try {
        const response = await problemDetailApi.getProblemById(id);
        if (response.code === 200 && response.data) {
          setProblemData(response.data);
          

        }
      } catch (error) {
        console.error('获取题目数据失败:', error);
        console.error('获取题目数据失败，无法加载题目信息');
      } finally {
        setLoading(false);
      }
    };
    
    fetchProblemData();
  }, [id]);
  


  const handleSelectProblem = async (problem: Problem) => {
    try {
      setLoading(true);
      const response = await problemDetailApi.getProblemById(problem.problemId);
      if (response.code === 200 && response.data) {
        setProblemData(response.data);
        // 更新URL
        window.history.pushState({}, '', `/problems/${problem.problemId}`);
      } else {
        message.error('获取题目详情失败');
      }
    } catch (error) {
      console.error('获取题目详情失败:', error);
      message.error('网络错误，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  // 防抖处理面板大小变化
  const handlePanelResize = useCallback(
    debounce((sizes: number[]) => {
      if (sizes.length >= 2) {
        const editorSize = showProblemPanel ? sizes[1] : sizes[0];
        setEditorPanelSize(editorSize);
      }
    }, 16), // 约60fps的更新频率
    [showProblemPanel]
  );

  // 防抖处理垂直面板大小变化
  const handleVerticalPanelResize = useCallback(
    debounce((sizes: number[]) => {
      if (sizes.length >= 2) {
        const resultSize = sizes[1];
        setResultPanelSize(resultSize);
      }
    }, 16),
    []
  );

  const handleCodeChange = (code: string) => {
    setStudentCode(code);
  };

  const handleLanguageChange = (language: string) => {
    setProgrammingLanguage(language);
  };

  const handleRunComplete = (result: { output: string; error: string; loading: boolean }) => {
    setOutput(result.output);
    setErrorMessage(result.error);
    setRunResultLoading(result.loading);
    if (!result.loading) {
      setRunResultActiveTab('result');
    }
  };

  const handleRunStart = () => {
    setRunResultLoading(true);
    setOutput('');
    setErrorMessage('');
    setRunResultActiveTab('result');
  };

  // 添加测试用例
  const handleAddTestCase = () => {
    const newTestCase: TestCase = { input: '', expectedOutput: '' };
    setTestCases([...testCases, newTestCase]);
  };

  // 删除测试用例
  const handleDeleteTestCase = (index: number) => {
    const newTestCases = [...testCases];
    newTestCases.splice(index, 1);
    setTestCases(newTestCases);
  };

  // 运行代码（在线自测）
  const handleRunCode = async () => {
    if (!studentCode.trim()) {
      message.warning('请先编写代码');
      setRunResultLoading(false);
      return;
    }
    
    if (testCases.length === 0) {
      message.warning('请先添加测试用例');
      return;
    }
    
    // 设置为在线自测模式
    setIsOnlineTest(true);
    handleRunStart();
    
    try {
      // 将编辑器语言映射到API所需的枚举值
      const languageMap: Record<string, string> = {
        'cpp': 'CPLUSPLUS',
        'java': 'JAVA',
        'python': 'PYTHON',
        'javascript': 'JAVASCRIPT',
        'csharp': 'CSHARP',
        'go': 'GO',
        'rust': 'RUST',
        'ruby': 'Ruby',
        'php': 'PHP'
      };
      
      const apiLanguage = languageMap[programmingLanguage] || 'CPLUSPLUS';
      
      const response = await problemDetailApi.executeCode({
        code: studentCode,
        language: apiLanguage,
        inputList: testCases,
        isAiJudge: false,
        isACM: false
      });
      
      const data = response.data;
      
      if (data) {
        // 处理判题信息，添加isPassed属性
        const processedJudgeInfo = data.judgeInfo?.map(info => ({
          ...info,
          isPassed: info.result === 1 // result为1表示通过
        })) || [];
        
        setJudgeInfo(processedJudgeInfo);
        setMemory(data.memory || 0);
        setTime(data.time || 0);
        setIsAccepted(data.accepted || false);
        setOutputList(data.outputList || []);
        setOutput(data.outputList?.join('\n') || '');
        // 在线自测时，如果有judgeInfo数据，不设置错误信息，让表格正常显示
        if (processedJudgeInfo.length > 0) {
          setErrorMessage('');
        } else {
          setErrorMessage(data.message || '');
        }
      } else {
        // 只有在没有data的情况下才使用外层message
        setErrorMessage('在线自测失败：' + (response.message || '未知错误'));
      }
    } catch (error) {
      console.error('在线自测出错:', error);
      setErrorMessage('服务器错误，请稍后再试');
    } finally {
      setRunResultLoading(false);
    }
  };
  


  const handleSubmitCode = async () => {
    if (!studentCode.trim() || !problemData?.problemEntityAdminVO) {
      setErrorMessage(problemData?.problemEntityAdminVO ? '请先编写代码' : '请先选择题目');
      return;
    }

    try {
      const response = await judgeApi.submitCode({
        code: studentCode,
        language: programmingLanguage as LanguageType,
        pid: Number(id),
        userId: 1, // 暂时hardcode用户ID
        submitId: 0, // 新提交时submitId为0
      });

      if (response.code === 1) {
        message.success('提交成功！');
      } else {
        message.error(response.message || '提交失败');
      }
    } catch (error) {
      console.error('提交代码出错:', error);
      message.error('服务器错误，请稍后再试');
    }
  };



  const getFullProblemDescription = (): string => {
    const problem = problemData?.problemEntityAdminVO;
    if (!problem) return '';

    return `
## ${problem.title}

${problem.problemId}: ${problem.title}

### 限制
- 时间限制: ${problem.timeLimit || 1000}ms
- 内存限制: ${problem.memoryLimit || 256}MB
`;
  };

  return (
    <Layout className="problem-detail-layout">
      <ProblemDetailHeader
        showProblemPanel={showProblemPanel}
        showResultPanel={showResultPanel}
        showAiPanel={showAiPanel}
        runResultLoading={runResultLoading}
        onToggleProblemPanel={() => setShowProblemPanel(!showProblemPanel)}
        onToggleResultPanel={() => setShowResultPanel(!showResultPanel)}
        onToggleAiPanel={() => setShowAiPanel(!showAiPanel)}
        onRunCode={handleRunCode}
        onSubmitCode={handleSubmitCode}
        onSelectProblem={handleSelectProblem}
      />
      


      <Content className="problem-detail-content">
        <PanelGroup direction="horizontal" className="main-panel-group" onLayout={handlePanelResize}>
          {/* 左侧题目面板 */}
          {showProblemPanel && (
            <>
              <Panel defaultSize={50} minSize={15} maxSize={60} className="problem-panel">
                <div className="panel-content">
                  <ProblemDescription 
                    problem={problemData?.problemEntityAdminVO}
                    timeLimit={problemData?.problemEntityAdminVO?.timeLimit}
                    memoryLimit={problemData?.problemEntityAdminVO?.memoryLimit}
                    tags={problemData?.tags}
                  />
                </div>
              </Panel>
              <PanelResizeHandle className="resize-handle-vertical" />
            </>
          )}

          {/* 中间编辑器和结果面板 */}
          <Panel defaultSize={showAiPanel ? 25 : 50} minSize={30} className="editor-panel">
            <PanelGroup direction="vertical" onLayout={handleVerticalPanelResize}>
              {/* 编辑器 */}
              <Panel defaultSize={showResultPanel ? 70 : 100} minSize={30} className="code-editor-panel">
                <CodeEditor
                  ref={codeEditorRef}
                  onCodeChange={handleCodeChange}
                  onLanguageChange={handleLanguageChange}
                  onRunStart={handleRunStart}
                  onRunComplete={handleRunComplete}
                  testCaseInput={testCaseInput}
                  initialCode={studentCode}
                  initialLanguage={programmingLanguage}
                />
              </Panel>

              {/* 运行结果面板 */}
              {showResultPanel && (
                <>
                  <PanelResizeHandle className="resize-handle-horizontal" />
                  <Panel defaultSize={50} minSize={9.5} maxSize={60} className="result-panel">
                    <div className="panel-content">
                      <Card
                        size="small"
                        title={
                          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                            <Tabs
                              activeKey={runResultActiveTab}
                              onChange={setRunResultActiveTab}
                              size="small"
                              items={[
                                { key: 'result', label: '运行结果' },
                                { key: 'testCase', label: '测试用例' },
                              ]}
                            />
                            {runResultActiveTab === 'testCase' && (
                              <Button type="primary" size="small" onClick={handleAddTestCase}>
                                添加测试用例
                              </Button>
                            )}
                          </div>
                        }
                        className="result-card"
                      >
                        <div>
                          {runResultActiveTab === 'testCase' && (
                            <div style={{ marginBottom: '10px' }}>
                              {testCases.map((testCase, index) => (
                                <div key={index} style={{ marginBottom: '16px', padding: '12px', border: '1px solid #f0f0f0', borderRadius: '6px', backgroundColor: '#fafafa' }}>
                                  <div style={{ marginBottom: '8px' }}>
                                    <strong>测试用例 {index + 1}</strong>
                                    <Button 
                                      size="small" 
                                      type="link" 
                                      danger 
                                      onClick={() => handleDeleteTestCase(index)}
                                      style={{ float: 'right' }}
                                    >
                                      删除
                                    </Button>
                                  </div>
                                  <div style={{ marginBottom: '8px' }}>
                                    <div style={{ marginBottom: '4px', fontSize: '12px', color: '#666' }}>输入：</div>
                                    <Input.TextArea
                                      rows={2}
                                      value={testCase.input}
                                      onChange={(e) => {
                                        const newTestCases = [...testCases];
                                        newTestCases[index] = { ...newTestCases[index], input: e.target.value };
                                        setTestCases(newTestCases);
                                      }}
                                      placeholder="请输入测试用例的输入数据"
                                      size="small"
                                    />
                                  </div>
                                  <div>
                                    <div style={{ marginBottom: '4px', fontSize: '12px', color: '#666' }}>预期输出：</div>
                                    <Input.TextArea
                                      rows={2}
                                      value={testCase.expectedOutput}
                                      onChange={(e) => {
                                        const newTestCases = [...testCases];
                                        newTestCases[index] = { ...newTestCases[index], expectedOutput: e.target.value };
                                        setTestCases(newTestCases);
                                      }}
                                      placeholder="请输入测试用例的预期输出"
                                      size="small"
                                    />
                                  </div>
                                </div>
                              ))}
                              {testCases.length === 0 && (
                                <div style={{ textAlign: 'center', color: '#999', padding: '20px' }}>
                                  暂无测试用例，请点击右上角添加按钮添加测试用例
                                </div>
                              )}
                            </div>
                          )}
                          
                          {(runResultActiveTab === 'result' || runResultActiveTab === 'testCase') && (
                             <RunResult
                               loading={runResultLoading}
                               output={output}
                               error={errorMessage}
                               testCaseInput={testCaseInput}
                               onTestCaseInputChange={setTestCaseInput}
                               activeTabKey={runResultActiveTab}
                               onTabChange={setRunResultActiveTab}
                               judgeInfo={judgeInfo}
                               isOnlineTest={isOnlineTest}
                               memory={memory}
                               time={time}
                               isAccepted={isAccepted}
                               outputList={outputList}
                             />
                           )}
                        </div>
                      </Card>
                    </div>
                  </Panel>
                </>
              )}
            </PanelGroup>
          </Panel>

          {/* 右侧AI面板 - 通过样式控制显示/隐藏 */}
          <PanelResizeHandle 
            className="resize-handle-vertical" 
            style={{ display: showAiPanel ? 'block' : 'none' }}
          />
          <Panel 
            defaultSize={25} 
            minSize={25}
            maxSize={40}
            className="ai-panel"
            style={{ display: showAiPanel ? 'block' : 'none' }}
          >
            <div className="panel-content">
              <AiChat
                visible={showAiPanel}
                onClose={() => setShowAiPanel(false)}
                problemDescription={getFullProblemDescription()}
                studentCode={studentCode}
                programmingLanguage={programmingLanguage}
                errorMessage={errorMessage}
                output={output}
                tags={problemData?.tags?.join('，')}
              />
            </div>
          </Panel>
        </PanelGroup>
      </Content>
      
      {/* 提交详情模态框 */}
      {selectedSubmitId && (
        <SubmissionDetail
          submitId={selectedSubmitId}
          visible={detailModalVisible}
          onClose={() => {
            setDetailModalVisible(false);
            setSelectedSubmitId(null);
          }}
        />
      )}
    </Layout>
  );
};

export default ProblemDetailPage;